<template>
	<view class="register-container">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="注册"
			:show-back="true"
			background-color="rgba(255, 255, 255, 0.95)"
			title-color="#333333"
			:border="true"
		/>
		
		
		<!-- 主要内容区域 -->
		<view class="content-wrapper">
			<!-- 头部标题 -->
			<view class="header-section">
				<text class="main-title">欢迎加入</text>
				<text class="sub-title">OceanBridge</text>
				<text class="desc-text">创建账户，开启海上购物新体验</text>
			</view>
			
			<!-- 注册表单 -->
			<view class="form-section">
				<view class="form-container">
					<!-- 邮箱输入 -->
					<view class="input-group">
						<view class="input-label">
							<text class="label-text">邮箱地址</text>
							<text class="required-mark">*</text>
						</view>
						<view class="input-wrapper" :class="{ 'input-error': errors.email }">
							<text class="input-icon">📧</text>
							<input
								class="input-field"
								type="text"
								v-model="formData.email"
								placeholder="请输入邮箱地址"
								@blur="validateEmail"
								@input="clearError('email')"
							/>
						</view>
						<text v-if="errors.email" class="error-text">{{ errors.email }}</text>
					</view>

					<!-- 用户名输入（可选） -->
					<view class="input-group">
						<view class="input-label">
							<text class="label-text">用户名</text>
							<text class="optional-mark">（可选）</text>
						</view>
						<view class="input-wrapper" :class="{ 'input-error': errors.username }">
							<text class="input-icon">👤</text>
							<input
								class="input-field"
								type="text"
								v-model="formData.username"
								placeholder="不填写将使用邮箱前缀作为用户名"
								@blur="validateUsername"
								@input="clearError('username')"
							/>
						</view>
						<text v-if="errors.username" class="error-text">{{ errors.username }}</text>
					</view>
					
					<!-- 密码输入 -->
					<view class="input-group">
						<view class="input-label">
							<text class="label-text">密码</text>
							<text class="required-mark">*</text>
						</view>
						<view class="input-wrapper" :class="{ 'input-error': errors.password }">
							<text class="input-icon">🔒</text>
							<input 
								class="input-field"
								:type="showPassword ? 'text' : 'password'"
								v-model="formData.password"
								placeholder="请输入密码（8-20位）"
								@blur="validatePassword"
								@input="clearError('password')"
							/>
							<text class="toggle-password" @click="togglePassword">
								{{ showPassword ? '👁️' : '👁️‍🗨️' }}
							</text>
						</view>
						<text v-if="errors.password" class="error-text">{{ errors.password }}</text>
					</view>
					
					<!-- 确认密码输入 -->
					<view class="input-group">
						<view class="input-label">
							<text class="label-text">确认密码</text>
							<text class="required-mark">*</text>
						</view>
						<view class="input-wrapper" :class="{ 'input-error': errors.confirmPassword }">
							<text class="input-icon">🔒</text>
							<input 
								class="input-field"
								:type="showConfirmPassword ? 'text' : 'password'"
								v-model="formData.confirmPassword"
								placeholder="请再次输入密码"
								@blur="validateConfirmPassword"
								@input="clearError('confirmPassword')"
							/>
							<text class="toggle-password" @click="toggleConfirmPassword">
								{{ showConfirmPassword ? '👁️' : '👁️‍🗨️' }}
							</text>
						</view>
						<text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>
					</view>
					
					<!-- 用户协议 -->
					<view class="agreement-section">
						<view class="checkbox-wrapper" @click="toggleAgreement">
							<view class="checkbox" :class="{ 'checkbox-checked': formData.agreeToTerms }">
								<text v-if="formData.agreeToTerms" class="checkbox-icon">✓</text>
							</view>
							<view class="agreement-text">
								<text class="agreement-prefix">我已阅读并同意</text>
								<text class="agreement-link" @click.stop="viewUserAgreement">《用户协议》</text>
								<text class="agreement-prefix">和</text>
								<text class="agreement-link" @click.stop="viewPrivacyPolicy">《隐私政策》</text>
							</view>
						</view>
						<text v-if="errors.agreement" class="error-text">{{ errors.agreement }}</text>
					</view>
					
					<!-- 注册按钮 -->
					<button
						class="register-btn"
						:class="{ 'btn-disabled': !canSubmit }"
						:disabled="!canSubmit"
						@click="handleRegister"
					>
						<text class="btn-text">{{ isLoading ? '注册中...' : '注册账户' }}</text>
					</button>

					<!-- 其他注册方式 -->
					<view class="alternative-register">
						<view class="divider">
							<view class="divider-line"></view>
							<text class="divider-text">其他注册方式</text>
							<view class="divider-line"></view>
						</view>

						<view class="alternative-buttons">
							<button class="btn btn-face face-register-btn" @click="goToFaceRegister">
								<text class="btn-icon">👤</text>
								<text>人脸注册</text>
							</button>
						</view>
					</view>
				</view>
			</view>


			<!-- 底部链接 -->
			<view class="footer-section">
				<text class="footer-text">已有账户？</text>
				<text class="footer-link" @click="goToLogin">立即登录</text>
				<text class="footer-text"> | </text>
				<text class="footer-link" @click="goToFaceLogin">人脸登录</text>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="注册中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { validateEmail as validateEmailUtil, validatePassword as validatePasswordUtil } from '../../utils/common.js'
import authApi from '../../api/auth.js'

// 全局状态
const store = inject('$store')

// 响应式数据
const formData = ref({
	email: '',
	username: '',
	password: '',
	confirmPassword: '',
	agreeToTerms: false
})

const errors = ref({})
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const isLoading = ref(false)

// 计算属性
const canSubmit = computed(() => {
	return formData.value.email && 
		   formData.value.password && 
		   formData.value.confirmPassword && 
		   formData.value.agreeToTerms &&
		   Object.keys(errors.value).length === 0 &&
		   !isLoading.value
})

// 表单验证方法
const validateEmail = () => {
	if (!formData.value.email) {
		errors.value.email = '请输入邮箱地址'
		return false
	}
	if (!validateEmailUtil(formData.value.email)) {
		errors.value.email = '请输入有效的邮箱地址'
		return false
	}
	delete errors.value.email
	return true
}

const validateUsername = () => {
	// 用户名是可选的，如果为空则不验证
	if (!formData.value.username) {
		delete errors.value.username
		return true
	}

	// 如果填写了用户名，则进行验证
	if (formData.value.username.length < 3 || formData.value.username.length > 20) {
		errors.value.username = '用户名长度应为3-20位'
		return false
	}

	// 用户名只能包含字母、数字、下划线
	const usernameRegex = /^[a-zA-Z0-9_]+$/
	if (!usernameRegex.test(formData.value.username)) {
		errors.value.username = '用户名只能包含字母、数字和下划线'
		return false
	}

	delete errors.value.username
	return true
}

const validatePassword = () => {
	if (!formData.value.password) {
		errors.value.password = '请输入密码'
		return false
	}
	if (!validatePasswordUtil(formData.value.password)) {
		errors.value.password = '密码长度应为8-20位，包含字母和数字'
		return false
	}
	delete errors.value.password
	
	// 如果确认密码已输入，重新验证确认密码
	if (formData.value.confirmPassword) {
		validateConfirmPassword()
	}
	return true
}

const validateConfirmPassword = () => {
	if (!formData.value.confirmPassword) {
		errors.value.confirmPassword = '请确认密码'
		return false
	}
	if (formData.value.password !== formData.value.confirmPassword) {
		errors.value.confirmPassword = '两次输入的密码不一致'
		return false
	}
	delete errors.value.confirmPassword
	return true
}

const validateAgreement = () => {
	if (!formData.value.agreeToTerms) {
		errors.value.agreement = '请同意用户协议和隐私政策'
		return false
	}
	delete errors.value.agreement
	return true
}

// 清除错误信息
const clearError = (field) => {
	if (errors.value[field]) {
		delete errors.value[field]
	}
}

// 切换密码显示
const togglePassword = () => {
	showPassword.value = !showPassword.value
}

const toggleConfirmPassword = () => {
	showConfirmPassword.value = !showConfirmPassword.value
}

const toggleAgreement = () => {
	formData.value.agreeToTerms = !formData.value.agreeToTerms
	if (formData.value.agreeToTerms) {
		clearError('agreement')
	}
}


// 表单提交
const handleRegister = async () => {
	// 验证所有字段
	const isEmailValid = validateEmail()
	const isUsernameValid = validateUsername()
	const isPasswordValid = validatePassword()
	const isConfirmPasswordValid = validateConfirmPassword()
	const isAgreementValid = validateAgreement()

	if (!isEmailValid || !isUsernameValid || !isPasswordValid || !isConfirmPasswordValid || !isAgreementValid) {
		return
	}

	try {
		isLoading.value = true

		// 使用用户输入的用户名，如果没有输入则使用邮箱前缀
		const username = formData.value.username || formData.value.email.split('@')[0]

		const response = await authApi.register({
			email: formData.value.email,
			password: formData.value.password,
			username: username
		})
		
		// 注册成功：如果后端返回 token，则直接自动登录
		const { accessToken, refreshToken, userId, username: respUsername } = response || {}
		if (accessToken) {
			const userInfo = {
				id: userId,
				username: respUsername || formData.value.email.split('@')[0],
				email: formData.value.email,
				emailVerified: false
			}
			store.actions.login(userInfo, accessToken, refreshToken)
			uni.showToast({ title: '注册并已登录', icon: 'success', duration: 1200 })
			setTimeout(() => {
				uni.reLaunch({ url: '/pages/index/index' })
			}, 800)
			return
		}
		// 否则仍按照邮箱验证流程
		uni.showToast({
			title: response?.message || '注册成功！请查收验证邮件',
			icon: 'success',
			duration: 2000
		})
		setTimeout(() => {
			uni.navigateTo({ url: `/pages/auth/email-verify?email=${encodeURIComponent(formData.value.email)}` })
		}, 2000)
		
	} catch (error) {
		console.error('注册失败:', error)
		
		// 处理特定的错误情况
		let errorMessage = '注册失败，请重试'
		if (error.message) {
			if (error.message.includes('邮箱已存在') || error.message.includes('already exists')) {
				errorMessage = '该邮箱已被注册，请使用其他邮箱或直接登录'
			} else if (error.message.includes('用户名已存在')) {
				errorMessage = '该用户名已被使用，请选择其他用户名'
			} else {
				errorMessage = error.message
			}
		}
		
		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 2000
		})
	} finally {
		isLoading.value = false
	}
}


// 页面跳转
const goToLogin = () => {
	uni.navigateBack({
		fail: () => {
			uni.reLaunch({
				url: '/pages/auth/login'
			})
		}
	})
}

const viewUserAgreement = () => {
	uni.navigateTo({
		url: '/pages/common/agreement?type=user'
	})
}

const viewPrivacyPolicy = () => {
	uni.navigateTo({
		url: '/pages/common/agreement?type=privacy'
	})
}

const goToFaceRegister = () => {
	uni.navigateTo({
		url: '/pages/auth/face-register'
	})
}

const goToFaceLogin = () => {
	uni.navigateTo({
		url: '/pages/auth/face-login'
	})
}
</script>

<style lang="scss" scoped>
.register-container {
	min-height: 100vh;
	background: #ffffff;
	position: relative;
	overflow: hidden;
}


.content-wrapper {
	position: relative;
	z-index: 1;
	padding: 100px 30px 40px;
}

.header-section {
	text-align: center;
	margin-bottom: 40px;
	padding: 25px 20px;
	background: rgba(0, 0, 0, 0.03);
	backdrop-filter: blur(15px);
	border-radius: 20px;
	border: 2px solid rgba(0, 0, 0, 0.15);
	box-shadow: 
		0 6px 24px rgba(0, 0, 0, 0.05),
		inset 0 1px 0 rgba(255, 255, 255, 0.8);
	
	.main-title {
		display: block;
		font-size: 32px;
		font-weight: bold;
		color: var(--text-color);
		margin-bottom: 8px;
	}
	
	.sub-title {
		display: block;
		font-size: 24px;
		font-weight: 600;
		color: var(--primary-color);
		margin-bottom: 12px;
	}
	
	.desc-text {
		display: block;
		font-size: 16px;
		color: var(--text-secondary);
	}
}

.form-section {
	margin-bottom: 30px;
}

.form-container {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 20px;
	padding: 30px 25px;
	backdrop-filter: blur(10px);
}

.input-group {
	margin-bottom: 20px;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.input-label {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
	
	.label-text {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
	}
	
	.required-mark {
		color: #ff4757;
		margin-left: 4px;
	}

	.optional-mark {
		color: #999999;
		font-size: 14px;
		margin-left: 4px;
	}
}

.input-wrapper {
	display: flex;
	align-items: center;
	background: #f8f9fa;
	border: 2px solid transparent;
	border-radius: 12px;
	padding: 0 16px;
	transition: all 0.3s ease;
	
	&:focus-within {
		border-color: var(--primary-color);
		background: #FFFFFF;
	}
	
	&.input-error {
		border-color: #ff4757;
		background: #fff5f5;
	}
}

.input-icon {
	font-size: 18px;
	margin-right: 12px;
	opacity: 0.6;
}

.input-field {
	flex: 1;
	height: 50px;
	font-size: 16px;
	color: #333333;
	background: transparent;
	border: none;
	outline: none;
}

.toggle-password {
	font-size: 18px;
	padding: 5px;
	cursor: pointer;
	opacity: 0.6;
	transition: opacity 0.3s ease;
	
	&:hover {
		opacity: 1;
	}
}

.error-text {
	display: block;
	font-size: 14px;
	color: #ff4757;
	margin-top: 6px;
	margin-left: 4px;
}

.agreement-section {
	margin: 25px 0;
}

.checkbox-wrapper {
	display: flex;
	align-items: flex-start;
	cursor: pointer;
}

.checkbox {
	width: 20px;
	height: 20px;
	border: 2px solid #ddd;
	border-radius: 4px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 12px;
	margin-top: 2px;
	transition: all 0.3s ease;
	flex-shrink: 0;
	
	&.checkbox-checked {
		background: var(--primary-color);
		border-color: var(--primary-color);
	}
	
	.checkbox-icon {
		color: #FFFFFF;
		font-size: 14px;
		font-weight: bold;
	}
}

.agreement-text {
	flex: 1;
	line-height: 1.5;
	
	.agreement-prefix {
		font-size: 14px;
		color: #666666;
	}
	
	.agreement-link {
		font-size: 14px;
		color: var(--primary-color);
		margin: 0 4px;
	}
}

.register-btn {
	width: 100%;
	height: 50px;
	background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
	border: none;
	border-radius: 12px;
	margin-top: 20px;
	transition: all 0.3s ease;
	box-shadow: 0 6px 20px rgba(0, 122, 255, 0.3);
	
	&:hover {
		background: linear-gradient(135deg, #0051D5 0%, #003A9B 100%);
		transform: translateY(-1px);
		box-shadow: 0 8px 24px rgba(0, 122, 255, 0.4);
	}
	
	&.btn-disabled {
		background: #ddd;
		cursor: not-allowed;
		box-shadow: none;
		transform: none;
	}
	
	.btn-text {
		font-size: 18px;
		font-weight: 600;
		color: #FFFFFF;
	}
}

	.alternative-register {
		margin-top: 24px;
	}

	.divider {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
	}

	.divider-line {
		flex: 1;
		height: 1px;
		background: rgba(0, 0, 0, 0.1);
	}

	.divider-text {
		padding: 0 16px;
		font-size: 14px;
		color: var(--text-secondary);
	}

	.alternative-buttons {
		display: flex;
		justify-content: center;
	}

	.btn-face {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #ffffff;
		border: none;
		border-radius: 16px;
		padding: 12px 24px;
		font-size: 14px;
		font-weight: 600;
		display: flex;
		align-items: center;
		gap: 8px;
		box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
		transition: all 0.3s ease;

		&:hover {
			transform: translateY(-2px);
			box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
		}
	}


.footer-section {
	text-align: center;
	margin-top: 30px;
	
	.footer-text {
		font-size: 16px;
		color: var(--text-secondary);
	}
	
	.footer-link {
		font-size: 16px;
		color: var(--primary-color);
		font-weight: 600;
		margin-left: 8px;
		text-decoration: underline;
	}
}

@keyframes float {
	0%, 100% {
		transform: translateY(0px);
	}
	50% {
		transform: translateY(-20px);
	}
}
</style>